<?php

namespace apiend\models;

use Yii;
use yii\base\Model;
use common\exceptions\ModelHttpException;
use common\models\share\ShareLog;

/**
 * 全局分享内容获取
 * ShareForm is the model behind the contact form.
 */
class ShareForm extends Model {

    /**
     * $id 类型对应内容的主键
     * @var integer
     */
    public $id;

    /**
     * $type 分享类型
     * @var string
     */
    public $type;

    /**
     * $user_id 用户 UID
     * @var integer
     */
    public $user_id;

    /**
     * $device_id 设备ID
     * @var integer
     */
    public $device_id;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['type', 'id'], 'required'],
            ['type', 'string', 'max' => 32],
            ['type', 'in', 'range' => ['dynamic', 'article', 'activity']],
            [['id', 'user_id', 'device_id'], 'integer'],
        ];
    }

    /**
     * Sends an email to the specified email address using the information collected by this model.
     *
     * @param string $email the target email address
     * @return bool whether the email was sent
     */
    public function share() {
        if (!$this->validate()) {
            throw new ModelHttpException('参数校验失败', $this->getFirstErrors());
        }
        if (!$this->shareData) {
            throw new ModelHttpException('分享信息不存在');
        }
        $data = $this->shareData;
        $data['id'] = 0;

        $model = new ShareLog();
        $model->attributes = [
            'model' => $this->type,
            'model_id' => $this->id,
            'content' => serialize($data),
            'user_id' => $this->user_id,
            'device_id' => $this->device_id,
        ];
        if ($model->save()) {
            $data['id'] = $model->id;
        } else {
            Yii::error($model->errors);
        }
        return $data;
    }

    public function getShareData() {
        if ($this->type == 'dynamic') {
            return \common\models\dynamic\Dynamic::findShareById($this->id);
        } elseif ($this->type == 'article') {
            return \common\models\tsline\TslineArticle::findShareById($this->id);
        }
        return null;
    }

}
